<?php

namespace SpecialOperations\GameBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use SpecialOperations\GameBundle\Entity\District;

/**
 * District controller.
 *
 * @Route("/district")
 */
class DistrictController extends Controller
{
    /**
     * Lists all District entities.
     *
     * @Route("/", name="district")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();
        $entities = $em->getRepository('SpecialOperationsGameBundle:District')->getPlayerDistricts($user->getId());

        return array('entities' => $entities);
    }

    /**
     * Finds and displays a District entity.
     *
     * @Route("/{id}/show", name="district_show")
     * @Template()
     */
    public function showAction($id)
    {
        
        $em = $this->getDoctrine()->getEntityManager();
        
        $entity = $em->getRepository('SpecialOperationsGameBundle:District')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find District entity.');
        }

        return $this->render('SpecialOperationsGameBundle:District:show.html.twig', array(
            'entity'      => $entity,
        ));
    }
    
    /**
     * Finds and displays a District entity.
     *
     * @Route("/{id}/build/{buildingType}", name="district_build")
     * @Template()
     */
    public function buildAction($id, $buildingType){
        $em = $this->getDoctrine()->getEntityManager();
        
        $entity = $em->getRepository('SpecialOperationsGameBundle:District')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find District entity.');
        }
        
        if($entity->getCapacity()>$entity->getBuildingsCount()){
            $building=$entity->getBuilding($buildingType);
            $entity->addToQueue($building, \SpecialOperations\GameBundle\Entity\QueuePosition::ACTION_BUILD);
            $em->persist($entity);
            $em->flush();
        }
        
        return $this->render('SpecialOperationsGameBundle:District:queue.html.twig', array(
            'district'      => $entity,
        ));

    }
    
    public function getQueueAction($district){
        $em = $this->getDoctrine()->getEntityManager();
        
        $entity = $em->getRepository('SpecialOperationsGameBundle:District')->find($district);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find District entity.');
        }
        
        
        return $this->render('SpecialOperationsGameBundle:District:queue.html.twig', array(
           'district'      => $entity,
        ));
    }

}
